// ignore_for_file: file_names, unnecessary_question_mark, unnecessary_this, slash_for_doc_comments

import 'package:mybase/base/tool/empty/FFEmpty.dart';
import 'package:mybase/base/tool/extension/FFListExt.dart';
import 'package:mybase/base/tool/globalMethod/FFSafeValue.dart';

/**扩展Map，安全取值*/
extension FFMapExt on Map {
  /**安全取值 */
  dynamic safeValue<T>(dynamic key) {
    if (key == null) return null;
    if (FFEmpty.mapIsEmpty(this)) return null;
    if (this.containsKey(key) == false) return null;

    dynamic tmp = this[key];
    if (tmp is T) {
      return tmp;
    }
    return null;
  }

  ///如果没有指定key,或者指定key对应的值为null，则插入
  bool safeInsert<T, V>(T key, V value) {
    if (this.containsKey(key)) {
      V? oldValue = globalSafeValueFromMap<V>(this, key);
      if (oldValue == null) {
        this[key] = value;
        return true;
      }
    } else {
      this[key] = value;
      return true;
    }

    return false;
  }

  // 如果value是 空/字符串空串，则去除key
  void removeEmptyValue() {
    var keys = this.keys.toList();
    int len = keys.length;
    for (int i = 0; i < len; i++) {
      String key = keys[i];
      var value = this[key];
      if (value == null) {
        this.remove(key);
      } else {
        if (value is String) {
          String valueStr = value;
          if (valueStr.isEmpty) {
            this.remove(key);
          }
        }
      }
    }
  }
}
